import {getUserToken} from './auth.ts';

// const baseURL: string = 'http://localhost:8081/sinpo';
// const baseURL: string = 'http://124.222.22.55:8087/sinpo';
const baseURL: string = 'https://www.tuanlianbao.com/api';

const Req = async (url: RequestInfo | URL, options: any = {
    method: 'GET',
    headers: {},
    body: null
}) => {
    const token = getUserToken();
    let body = null;
    if (options.body && options.body instanceof FormData) {
        body = options.body;
    } else {
        body = options.body ? JSON.stringify(options.body) : null;
    }
    const response = await fetch(baseURL + url, {
        method: options.method,
        headers: {
            'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + token,
            ...options.headers
        },
        body
    });

    if (!response.ok) {
        throw new Error('请求失败');
    }

    return response.json();
};


const UploadFile = async (fileType: number, file: File) => {
    const formData = new FormData();
    formData.append('file', file);
    const token = getUserToken();
    const response = await fetch(baseURL + '/upload/file?fileType=' + fileType, {
        method: 'POST',
        headers: {
            'Authorization': 'Bearer ' + token,
        },
        body: formData
    });
    return response.json();
}

export {Req, UploadFile}